var md5 = require("../public/common/md5");
var fs = require("fs");
var hasLock = false;//多进程操作文件加锁机制
replaceAll = function(str, s1,s2) {
    return str.replace(new RegExp(s1,"gm"),s2);
}
function isEmptyObject(e) {
    var t;
    for (t in e)
        return !1;
    return !0
}
function getLeaveObj(cacheMap, pathItems, contentMd5) {
    for(var index = 0; index < pathItems.length; index++) {
        var nextLeaveObj = cacheMap[pathItems[index]];
        var name = pathItems[index];
        if(!nextLeaveObj) {
            if(index != pathItems.length - 1) {
                cacheMap = cacheMap[pathItems[index]] = {};
            } else {
                cacheMap[pathItems[index]] = contentMd5;
            }
        } else {
            if(!isEmptyObject(nextLeaveObj) && typeof nextLeaveObj != "string") {
                cacheMap = cacheMap[pathItems[index]];
            } else {
                cacheMap[pathItems[index]] = contentMd5;
            }
        }
    }
}
var cacheMapWatcher = {
    updateCacheMap: function(path, content) {
            if (path.indexOf("public/common") > -1 || path.indexOf("public/component") > -1) {
                return;
            }
            var cache = JSON.parse(fs.readFileSync("cacheMap.js"));
            var cacheMap = cache["javascripts"];
            var pathItems = path.split("/");
            pathItems.splice(0, 2);
            var contentMd5 = md5(content);
            getLeaveObj(cacheMap, pathItems, contentMd5);
            if (path.indexOf("widget") != -1) {//如果是widget
                var cssPath = replaceAll(path, ".js", ".css");
                var cssContentMd5 = md5(fs.readFileSync(cssPath).toString());
                pathItems = cssPath.split("/");
                pathItems.splice(0, 2);
                getLeaveObj(cacheMap, pathItems, cssContentMd5);
            }
            var cacheMapJson = JSON.stringify(cache, null, 2);
            fs.writeFileSync("cacheMap.js", cacheMapJson);
    },
    clearCacheMap: function() {
        var cache = JSON.parse(fs.readFileSync("cacheMap.js"));
        if(isEmptyObject(cache.javascripts)) {
            return;
        }
        cache.javascripts = {};
        var cacheMapJson = JSON.stringify(cache, null, 2);
        fs.writeFileSync("cacheMap.js", cacheMapJson);
    }
}
module.exports = cacheMapWatcher;